import datetime
import os
import sys

from PyQt5.QtWidgets import *
from docx import Document
from docx.shared import Pt
from calc_interface import Ui_MainWindow

global e_view
global op_temp, operator_flag, ans_temp
operator_flag = 0
pluginsPath = 'PyQt5/Qt/plugins'
if os.path.exists(pluginsPath):  # 指定插件路径。源码运行时不会生效，打包后运行检测到路径，加载插件
    QApplication.addLibraryPath(pluginsPath)


class MyMainWindow(QMainWindow, Ui_MainWindow):

    def forge_link(self):
        self.b_0.clicked.connect(self.button_event(0))
        self.b_1.clicked.connect(self.button_event(1))
        self.b_2.clicked.connect(self.button_event(2))
        self.b_3.clicked.connect(self.button_event(3))
        self.b_4.clicked.connect(self.button_event(4))
        self.b_5.clicked.connect(self.button_event(5))
        self.b_6.clicked.connect(self.button_event(6))
        self.b_7.clicked.connect(self.button_event(7))
        self.b_8.clicked.connect(self.button_event(8))
        self.b_9.clicked.connect(self.button_event(9))
        self.b_add.clicked.connect(self.button_event('+'))
        self.b_sub.clicked.connect(self.button_event('-'))
        self.b_mul.clicked.connect(self.button_event('*'))
        self.b_div.clicked.connect(self.button_event('/'))
        self.b_pow.clicked.connect(self.button_event('**'))
        self.b_bra_l.clicked.connect(self.button_event('('))
        self.b_bra_r.clicked.connect(self.button_event(')'))
        self.b_mod.clicked.connect(self.button_event('%'))
        self.b_pai.clicked.connect(self.clear_log)
        self.b_pt.clicked.connect(self.button_event('.'))
        self.b_del.clicked.connect(self.delete_event)
        self.b_clc.clicked.connect(self.clear_all)
        self.b_eq.clicked.connect(self.calc_complish)
        self.b_out.clicked.connect(self.output_word)

    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.setupUi(self)
        self.forge_link()  # 连接槽函数

    def button_event(self, arg):
        # print(dir(self.e_view))
        global e_view
        e_view = self.e_view

        def fun():  # 返回一个自定义的槽函数
            global e_view
            txt = e_view.toPlainText()
            e_view.setText(txt + str(arg))  # 在输入文本后添加字符
        return fun

    def calc_complish(self):
        txt = self.e_view.toPlainText()
        global op_temp, ans_temp
        global operator_flag

        operator = self.get_operator(txt)  # 对乘除取操作数
        print("operator", operator)
        # 对操作符号进行保留添加
        if operator:
            op_temp = operator
            print("op_temp", op_temp)

        if not self.contain_symbol(txt):  # 没有包含操作数
            print("没有包含操作数")
            if op_temp and operator_flag == 1:
                print("有保留的操作数,且第一次拼接", op_temp)
                txt = txt + op_temp  # 重复上一次操作
                self.cal_process(txt)
            elif ans_temp and operator_flag != 1:
                print("拼接上一次有操作数时的结果")
                txt = txt + "*" + ans_temp
                self.cal_process(txt)
            else:
                print("防止出现不动的情况")
                self.cal_process(txt)
        else:
            print("包含了操作数")
            self.cal_process(txt)

    def cal_process(self, txt):
        ans_show = ""
        try:
            ans = str(eval(txt))
            if ans.find("e") != -1:
                ans_show = self.deal_data(ans)
                print("ans_show", ans_show)
            else:
                ans_interface = ans
                if ans_interface.find(".") == -1:
                    if len(ans_interface) > 12:
                        ans_interface = float(ans_interface)
                        ans_interface = "{:.14e}".format(ans_interface)
                        ans_show = self.deal_data(ans_interface)
                        print("ans_show", ans_show)
                else:
                    ans_interface = float(ans_interface)
                    ans_interface = "{:.14e}".format(ans_interface)
                    temp = ans_interface
                    temp = temp.split(".")[0] + "." + temp.split(".")[1][:9]
                    ans_show = temp
        except BaseException:
            print("计算过程有误")
            ans = 'MathError'
        # print(ans)
        self.clear_event()
        self.e_view.setText(ans)
        if ans_show != "":
            self.l_hist.addItem(str(ans_show))
        if ans != "MathError":
            return ans

    def get_operator(self, txt):
        global operator_flag, ans_temp
        mul = txt.find("*")
        div = txt.find("/")
        # plus = txt.find("+")
        # sub = txt.find("-")
        # collect = [mul, div, plus, sub]
        collect = [mul, div]
        op_list = []
        index = max(collect)
        if index != -1:
            operator_flag += 1
            for i in collect:
                if i != -1:
                    op_list.append(i)
            ans_temp = txt[:min(op_list)]
            operator = txt[min(op_list):]
            return operator
        else:
            return False

    def deal_data(self, ans_interface):
        ans_interface = ans_interface.split("e")
        print("ans_interface", ans_interface)
        if int(ans_interface[1]) < -100:
            ans_show = ""
            print("输出小于-100次方")
        elif int(ans_interface[1]) >= 100:
            ans_show = ""
            print("输出大于100次方")
        elif len(ans_interface[0]) > 11:
            temp = ans_interface[0]
            temp = temp.split(".")[0] + "." + temp.split(".")[1][:7]
            ans_show = str(temp) + str(ans_interface[1])
        return ans_show

    def contain_symbol(self, text):
        symbols = "+-*/"
        if text.find("e-") != -1:
            text = text.replace("e-", "")
        elif text.find("e+") != -1:
            text = text.replace("e+", "")
        if text.find("-") == 0:
            text = text.replace("-", "", 1)
        for symbol in symbols:
            if symbol in text:
                return True
        return False

    def clear_all(self):
        global op_temp, operator_flag, ans_temp
        op_temp = ""
        operator_flag = 0
        ans_temp = ""
        self.e_view.setText('')

    def clear_event(self):
        self.e_view.setText('')

    def clear_log(self):
        self.l_hist.clear()

    def delete_event(self):
        txt = self.e_view.toPlainText()
        txt = txt[:len(txt) - 1]
        self.e_view.setText(txt)

    def output_word(self):  # 保存为word
        result = []
        cout = self.l_hist.count()
        try:
            if os.path.exists("./运算结果.docx"):
                Doc = Document("运算结果.docx")
            else:
                Doc = Document()
            style = Doc.styles['Normal']
            font = style.font
            font.name = 'Times New Roman'
            font.size = Pt(15)
            for i in range(cout):
                result.append(self.l_hist.item(i).text())
            print(result)
            now = datetime.datetime.now().strftime("%Y-%m-%d, %H:%M:%S")
            Doc.add_paragraph("---"+now+"---")
            for e in result:
                Doc.add_paragraph(e)
            Doc.save("运算结果.docx")
        except Exception as e:
            print("写入文档出错", e)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    myWin = MyMainWindow()
    myWin.show()
    sys.exit(app.exec())
